package com.to8to.scene.server;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.kitt.esb.DefaultServerDeamon;
import com.to8to.kitt.esb.NodeChangeEvent;
import com.to8to.kitt.utils.LogUtils;
import com.to8to.scene.aop.LogAdviceImpl;
import com.to8to.scene.aop.ProxyFactory;
import com.to8to.thrift.diary.service.SceneDiaryService;

public class SceneDiaryServer extends DefaultServerDeamon
{
    public static Logger logger = LoggerFactory.getLogger(SceneDiaryServer.class);
    public static String LOGBACKConfPath = "crm/common/logback.xml";

    @Override
    public void onPrivateConfigChange(Map<String, NodeChangeEvent> config)
    {
        String[] keys = { "common.properties", "index.json" };
        for (String file_name : keys)
        {
            NodeChangeEvent event = config.get(file_name);

            if (!event.isChange())
                continue;

            System.out.println("加载配置: " + file_name);
            System.out.println("New Data :" + new String(event.ndata));

            byte[] data = event.ndata;

            switch (file_name)
            {
                case "common.properties":
                {
                    Commons.init(data);
                    break;
                }
                case "index.json":
                {
                    InputStream index_input = new ByteArrayInputStream(data);
                    Tables.ensureAllIndexes(Commons.mongo, index_input);
                }
            }
        }

        super.onPrivateConfigChange(config);
    }

    @Override
    public void onCommonConfigChange(NodeChangeEvent e)
    {
        if (e.isChange() && e.path.contains(LOGBACKConfPath))
        {
            String logbackConfig = new String(e.ndata);
            String real = logbackConfig.replace("${java.service}", service).replace("${java.instance}", instance);
            System.out.println("加载logback.xml:\n" + real);
            LogUtils.resetConfigByData(real);
        }
    }

    public static void main(String[] args)
    {
        String ins = "server_2";

        if (args.length > 0)
            ins = args[0];

        SceneDiaryIface iface = new SceneDiaryIface();
        SceneDiaryService.Iface proxy = (SceneDiaryService.Iface) ProxyFactory.getProxy(iface, new LogAdviceImpl());
        SceneDiaryServer server = new SceneDiaryServer();
        server.addCommonConfigPath(LOGBACKConfPath);
        server.start(proxy, SceneDiaryService.class, ins);
    }
}
